package org.sgx.gwteditors.client.impl1.simple;

import java.util.List;

import org.sgx.gwteditors.client.editor.Editor;
import org.sgx.gwteditors.client.editor.error.AbstractEditorError;
import org.sgx.gwteditors.client.editor.error.EditorError;
import org.sgx.gwteditors.client.editor.error.EditorErrorManager;
import org.sgx.gwteditors.client.editor.event.EditorEventManager;
import org.sgx.gwteditors.client.editor.event.EditorValueChangeEvent;
import org.sgx.gwteditors.client.editor.event.ValueChangeListener;
import org.sgx.gwteditors.client.impl1.EditorFramework1;
import org.sgx.gwteditors.client.impl1.EditorManager1;
import org.sgx.gwteditors.client.util.Util;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class DoubleEditorEntry extends TextBox implements Editor<Double>, 
ValueChangeHandler<String> {

	@Override
	public boolean isSimple() {
		return true;
	}
	public DoubleEditorEntry() {
		super();
		addValueChangeHandler(this);
	}
	@Override
	public Double flush() {
		try {
			return Util.parseDouble(getText(), 0);
		} catch (Exception e) {
			EditorErrorManager.<Double>getInstance().setError(this, 
				new AbstractEditorError<Double>(getText()+ 
				" is not a valid number ", this));
			return null;
		}
	}

	@Override
	public void load(Double t) {
		setText(t+"");
	}

	@Override
	public Widget getWidget() {
		return this;
	}

	@Override
	public void addValueChangeListener(ValueChangeListener<Double> l) {
		EditorEventManager.<Double>getInstance().addValueChangeListener(this, l);
	}

	@Override
	public void removeValueChangeListener(ValueChangeListener<Double> l) {
		EditorEventManager.<Double>getInstance().removeValueChangeListener(this, l);
	}
//	@Override
//	public void onValueChange(ValueChangeEvent<Integer> event) {
//		EditorEventManager.<Integer>getInstance().fireValueChangeGwtEvent(this, event);	
//	}
	@Override
	public void onValueChange(ValueChangeEvent<String> event) {
		EditorValueChangeEvent<Double> ev_ = new EditorValueChangeEvent<Double>(this, flush(), null);		
		EditorEventManager.<Double>getInstance().fireValueChangeEvent(this, ev_);	
	}
	@Override
	public List<EditorError<Double>> getErrors() {
		return EditorErrorManager.<Double>getInstance().getErrors(this);
	}
	@Override
	public String getEditorId() {
		return EditorManager1.getInstance().getEditorName(this);		
	}

	@Override
	public String[] getEditorTypesSupported() {
		return new String[]{EditorFramework1.TYPE_DOUBLE}; 
	}
}
